package yyee.llee.mmee.net.interceptor

import yyee.llee.mmee.net.HttpManager.BASE_URL_FOR_ARI
import yyee.llee.mmee.net.HttpManager.BASE_URL_FOR_CALENDAR
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

class ReplaceBaseUrlInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request()
        val oldUrl: HttpUrl = request.url()
        val builder: Request.Builder = request.newBuilder()
        var newUrl: HttpUrl? = null
        if (oldUrl.url().toString().contains("/environment/air/cityair")
            || oldUrl.url().toString().contains("/environment/air/pm")
        ) {
            newUrl = HttpUrl.parse(BASE_URL_FOR_ARI)
            //重建新的HttpUrl，修改需要修改的url部分
            val newFullUrl: HttpUrl = oldUrl
                .newBuilder()
                .host(newUrl!!.host()) //更换主机名
                .port(newUrl.port()) //更换端口
                .build()
            return chain.proceed(builder.url(newFullUrl).build());
        }

        if (oldUrl.url().toString().contains("/calendar/day")) {
            newUrl = HttpUrl.parse(BASE_URL_FOR_CALENDAR)
            //重建新的HttpUrl，修改需要修改的url部分
            val newFullUrl: HttpUrl = oldUrl
                .newBuilder()
                .host(newUrl!!.host()) //更换主机名
                .port(newUrl.port()) //更换端口
                .build()
            return chain.proceed(builder.url(newFullUrl).build());
        }

        return chain.proceed(request)
    }
}